import ast
import socket

from utils.constant_jijin import setParams, getJiJin, setJiJin
from utils.thread_util import createThread, destroyThread


class SocketJiJin:
    '''
    集金网 MT5 socket服务
    '''
    global address, port
    address = "127.0.0.1"
    port = 6661

    def start(self):
        self.thread = createThread(self.clockLooper)
        self.thread.start()

    def destroy(self):
        destroyThread(self.thread)

    def clockLooper(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((address, port))
        self.sock.listen(1)
        while True:
            print("等待连接socket服务")
            self.conn, self.addr = self.sock.accept()
            print('socket已连接:{0}'.format(self.addr))
            while True:
                data = self.conn.recv(10000)
                if not data:
                    break
                celve = getJiJin()
                jsonObj = ast.literal_eval(data.decode())
                if jsonObj["status"] == "ok":
                    setParams(jsonObj["symbol"], jsonObj["period"], jsonObj["mode"])
                    self.conn.send(bytes("ok", "utf-8"))

                if celve != "" and jsonObj["status"] == "123":
                    if celve[-1] == "_":
                        celve = celve[0:-1]
                    self.conn.send(bytes(celve, "utf-8"))
                    setJiJin("")
            self.conn.close()
        self.sock.close()

    def __del__(self):
        self.sock.close()


if __name__ == '__main__':
    SocketJiJin().start()
